<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import type { FormInstance } from 'ant-design-vue'
import { message } from 'ant-design-vue'
import useUserList from './userList'
import useRoleList from '@/views/sysAuth/role/roleList'
import md5 from 'blueimp-md5'
import { PRIVATE_KEY } from '@/common/config'
import { PlusOutlined } from '@ant-design/icons-vue'
import { uploadFile } from '@/common/utils'

const emits = defineEmits(['close'])
const props = defineProps<{
	visible: boolean
	title: string
	editUser: { [key: string]: any }
}>()

type avatarFile = {
	uid: number | string
	name: string
	status: 'done' | 'uploading' | 'error'
	url: string
	[key: string]: any
}

interface userFormType {
	userName: string
	password: string
	nickName: string
	phone:string
	roleIds: string[]
	avatarList: avatarFile[]
	[key: string]: any
}
const userState = reactive<userFormType>({
	userName: '',
	password: '',
	nickName: '',
	phone:'',
	roleIds: [],
	avatarList: [],
})
const formInstance = ref<FormInstance | null>(null)
const isSuccessOperate = ref(false)
const userList = useUserList()
const roleList = useRoleList()
const roleNameList = ref<{ label: string; value: string }[]>([])
const confirmLoading = ref(false)

const formLayout = {
	style: 'margin: 0 10px',
	labelCol: { span: 6 },
	wrapperCol: { span: 18 },
	labelAlign: 'left',
}
const rowFormItemLayout = {
	labelCol: { span: 3 },
	wrapperCol: { span: 21 },
}
const rules = {
	userName: [{ required: true, message: '请输入用户名！', trigger: 'change' }],
	password: [{ required: false, message: '请输入密码！', trigger: 'change' }],
	phone:[{pattern: /^\d{11}$/, message: '请输入正确格式的手机号!'}],
	roleIds: [{ required: true, message: '请选择角色！', trigger: 'change' }],
	nickName: [{ required: true, message: '请输入昵称！', trigger: 'change' }],
}
function showBack() {
	formInstance.value?.resetFields()
	Object.keys(props.editUser).forEach((k) => {
		if (k != 'password' && k != 'roleIds' && k != 'avatarList') userState[k] = props.editUser[k]
		if (k == 'roleIds') userState.roleIds = props.editUser.roleIds.split(',')
		if (k == 'avatarList') {}
	})
}
function getRoleListName() {
	roleNameList.value = roleList.list.map((v) => {
		return { label: v.roleName, value: v.id as string }
	})
}

function handleDropUploadAvatar(e: any) {
	console.log(e, 'drop')
}
function handlePreviewAvatar(e: any) {
	console.log(e, 'priview')
}
function handleRemoveAvatar(e: any) {
	console.log(e, 'remove')
}
function handleUploadAvatar(e: any) {
	console.log(e, 'upload')
	// uploadFile(e.file)
}

async function handleOk() {
	try {
		const values = await formInstance.value?.validate()

		let roleIds = '',
			roleNames = ''
		roleNameList.value.forEach((v) => {
			if (userState.roleIds.includes(v.value)) {
				if (!roleIds) roleIds = v.value
				else roleIds += ',' + v.value
				if (!roleNames) roleNames = v.label
				else roleNames += ',' + v.label
			}
		})

		let params: userType
		if (!values!.password) {
			delete values!.password
			params = { ...props.editUser, ...(values as userFormType), roleIds, roleNames, id: props.editUser.id }
		} else params = { ...props.editUser, ...(values as userFormType), password: md5((values as userFormType).password, PRIVATE_KEY), roleIds, roleNames, id: props.editUser.id }
		delete params.avatarList
		const res = await userList.updateItem(params)
		if (res.code == 200) {
			isSuccessOperate.value = true
			emits('close', isSuccessOperate.value)
		} else if (res.code == 201) message.error('用户名已存在！')
	} catch (error) {
		console.log(error)
	}
}

// 监视的是对象的某个属性，必须使用回调方式
watch(
	() => props.visible,
	(nv) => {
		if (nv) {
			isSuccessOperate.value = false
			getRoleListName()
			showBack()
		}
	}
)
</script>

<template>
	<a-modal :visible="visible" :title="title" :maskClosable="false" :mask="false" width="80%" @ok="handleOk" @cancel="emits('close')" :confirmLoading="confirmLoading">
		<a-form :model="userState" :rules="rules" v-bind="formLayout" ref="formInstance" name="route_update">
			<a-row :gutter="[24, 8]">
				<a-col :span="12">
					<a-form-item name="userName" label="用户名">
						<a-input v-model:value="userState.userName" placeholder="用户名必须唯一" allowClear />
					</a-form-item>
				</a-col>

				<a-col :span="12">
					<a-form-item name="password" label="密码">
						<a-input-password v-model:value="userState.password" placeholder="请输入密码" allowClear />
					</a-form-item>
				</a-col>

				<a-col :span="12">
					<a-form-item name="nickName" label="昵称">
						<a-input v-model:value="userState.nickName" placeholder="请输入昵称" allowClear />
					</a-form-item>
				</a-col>

				<a-col :span="12">
					<a-form-item name="phone" label="手机号">
						<a-input v-model:value="userState.phone" placeholder="请输入手机号" allowClear />
					</a-form-item>
				</a-col>

				<a-col :span="24">
					<a-form-item name="roleIds" label="拥有的角色" v-bind="rowFormItemLayout">
						<a-select mode="multiple" v-model:value="userState.roleIds" placeholder="请选择拥有的角色" :options="roleNameList" optionFilterProp="label" allowClear />
					</a-form-item>
				</a-col>

				<a-col :span="24">
					<a-form-item name="avatarList" label="头像" v-bind="rowFormItemLayout">
						<a-upload
							accept=".png, .jpg, .jpeg"
							v-model:file-list="userState.avatarList"
							list-type="picture-card"
							:show-upload-list="{ showDownloadIcon: false, showPreviewIcon: false, showRemoveIcon: true }"
							@priview="handlePreviewAvatar"
							@remove="handleRemoveAvatar"
							@drop="handleDropUploadAvatar"
							:customRequest="handleUploadAvatar"
						>
							<div v-if="!userState.avatarList.length">
								<plus-outlined />
								<div style="margin-top: 8px">点击上传</div>
							</div>
						</a-upload>
					</a-form-item>
				</a-col>
			</a-row>
		</a-form>
	</a-modal>
</template>
